package com.yusp75.myexam.ui.books

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.fragment.navArgs
import com.yusp75.myexam.com.yusp75.myexam.ui.books.BookAdapter
import com.yusp75.myexam.com.yusp75.myexam.util.ProgressState
import com.yusp75.myexam.databinding.FragmentBookListBinding
import com.yusp75.myexam.ui.display.DisplayFragmentArgs
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.getValue


class BookListFragment : Fragment() {
    private val viewModel: BookViewModel by viewModel()
    private lateinit var binding: FragmentBookListBinding
    private lateinit var selectedFile: TextView

    // 使用新版Activity Result API注册文件选择回调
    private val filePickerLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        result.data?.data?.also { uri ->
            if (isValidXlsx(uri)) {
                selectedFile.text = uri.path
                // 处理
                viewModel.processFile(binding.root.context, null, uri)
            } else {
                Toast.makeText(context, "无效文件类型", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        binding = FragmentBookListBinding.inflate(inflater)

        selectedFile = binding.textSelectedFile
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        // 传递适配器函数
        val adapter = BookAdapter(
            { book -> viewModel.selectBook(book) },
            { book -> viewModel.deleteBook(book) }
        )
        // 书籍清单
        binding.bookRecyclerView.adapter = adapter

        viewLifecycleOwner.lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.books.collect { books ->
                    adapter.submitList(books)
                }
            }
        }

        // 选择文件
        binding.btnSelectFile.setOnClickListener {
            openFile()
        }
        // 观察处理状态
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.progressState.collect { state ->
                    when (state) {
                        is ProgressState.Processing -> {
                            binding.progressBar.visibility = View.VISIBLE
                            binding.progressBar.progress = state.progress
                        }

                        ProgressState.Completed -> {
                            binding.progressBar.visibility = View.GONE
                            Toast.makeText(context, "处理完成", Toast.LENGTH_SHORT).show()
                        }

                        is ProgressState.Error -> {
                            Log.e("BookList fragment", "导入题目时发生错误: ${state.message}")
                            binding.progressBar.visibility = View.GONE
                            Toast.makeText(context, "错误: ${state.message}", Toast.LENGTH_LONG)
                                .show()
                        }

                        else -> Unit
                    }
                }
            }
        }

        // 参数： 文件名
        val args: BookListFragmentArgs by navArgs()
        val fileName = args.fileName
        binding.fileStatus.text = when {
            fileName == "未拷贝" -> "拷贝默认文件失败，单独拷贝题目文件到[下载]目录"
            fileName.isNotEmpty() -> "已拷贝 $fileName 在[下载]目录"
            else -> ""
        }
        binding.fileStatus.visibility = when {
            fileName.isEmpty() -> View.GONE
            else -> View.VISIBLE
        }
    }

    // 打开文件对话框
    private fun openFile() {
        val intent = Intent(Intent.ACTION_GET_CONTENT).apply {
            type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            //Name: /xl/workbook.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml
            //type = "*/*"
            addCategory(Intent.CATEGORY_OPENABLE)
        }
        filePickerLauncher.launch(intent)
    }

    private fun isValidXlsx(uri: Uri): Boolean {
        return context?.contentResolver?.getType(uri)?.contains("spreadsheetml") == true ||
                uri.path?.endsWith(".xlsx", ignoreCase = true) == true
    }

    //
}